package cn.iotab.iotkit.transport.api.common.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

public class JsonUtil {

    public static <T> T toObject(byte[] data, Class<T> tClass) {
        return JSON.parseObject(data, tClass);
    }

    public static <T> T toObject(String data, Class<T> tClass) {
        return JSON.parseObject(data, tClass);
    }

    public static String toJsonString(Object obj) {
        return JSON.toJSONString(obj);
    }

    public static byte[] toJsonBytes(Object obj) {
        return JSON.toJSONBytes(obj);
    }

    public static <S> JSONObject toJsonObject(S source){
        if (source == null){
            return new JSONObject();
        }
        Object obj = JSONObject.toJSON(source);
        if (obj instanceof JSONObject){
            return (JSONObject) obj;
        }
        throw new IllegalArgumentException("can't convert " + source.getClass().getName() + " to JSONObject");
    }
}
